package com.pachong.android.frameworkbase.utils;


import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;

/**
 * Created by storm on 14-5-9.
 */
public class DimensionUtil {
    private static int screenWidthPx; //屏幕宽 px
    private static int screenHeightPx; //屏幕高 px
    private static float density;//屏幕密度
    private static int densityDpi;//屏幕密度
    private static float screenWidthDip;//  dp单位
    private static float screenHeightDip;//  dp单位

    public static void init(Context context, Resources resources) {
        DisplayMetrics dm = resources.getDisplayMetrics();
        DimensionUtil.density = dm.density;
        DimensionUtil.densityDpi = dm.densityDpi;
        DimensionUtil.screenWidthPx = dm.widthPixels;
        DimensionUtil.screenHeightPx = dm.heightPixels;
        DimensionUtil.screenWidthDip = DimensionUtil.px2dip(context, dm.widthPixels);
        DimensionUtil.screenHeightDip = DimensionUtil.px2dip(context, dm.heightPixels);
    }


    public static int getScreenWidthPx() {
        if (screenWidthPx <= 0) {
            throw new RuntimeException("请在Application 中调用初始化方法");
        }
        return screenWidthPx;
    }

    public static int getScreenHeightPx() {
        if (screenHeightPx <= 0) {
            throw new RuntimeException("请在Application 中调用初始化方法");
        }
        return screenHeightPx;
    }

    public static float getDensity() {
        if (density <= 0) {
            throw new RuntimeException("请在Application 中调用初始化方法");
        }
        return density;
    }

    public static int getDensityDpi() {
        if (densityDpi <= 0) {
            throw new RuntimeException("请在Application 中调用初始化方法");
        }
        return densityDpi;
    }

    public static float getScreenWidthDip() {
        if (screenWidthDip <= 0) {
            throw new RuntimeException("请在Application 中调用初始化方法");
        }
        return screenWidthDip;
    }


    public static float getScreenHeightDip() {
        if (screenHeightDip <= 0) {
            throw new RuntimeException("请在Application 中调用初始化方法");
        }
        return screenHeightDip;
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}
